package com.kexuexiong.demo.bear.common.multiDataSource.aop;

import com.kexuexiong.demo.bear.common.multiDataSource.DataSourceContextHolder;
import com.kexuexiong.demo.bear.common.multiDataSource.annotation.SwitchDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
@Order(1)
@Slf4j
public class SwitchDataSourceAspect {

    @Pointcut("@annotation(com.kexuexiong.demo.bear.common.multiDataSource.annotation.SwitchDataSource)")
    public void switchDataSource() {

    }

    @Around("switchDataSource()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(SwitchDataSource.class)) {
            SwitchDataSource apiOperation = method.getAnnotation(SwitchDataSource.class);
            log.info("切换数据源：{}", apiOperation.value());
            DataSourceContextHolder.setContext(apiOperation.value());
        }
        Object result = joinPoint.proceed();
        return result;
    }
}
